package com.black.common.feign;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author linwenfeng
 */
public abstract class AbstractRestClient implements RestApi {

    @Resource
    private RestTemplate restTemplate;

    @Override
    public HttpMethod getHttpMethod() {
        return HttpMethod.POST;
    }

    @Override
    public LinkedMultiValueMap<String, String> getHttpBasicHeader() {
        LinkedMultiValueMap<String, String> header = new LinkedMultiValueMap<>();
        header.add("accept", "*/*");
        header.add("Content-Type", "application/json;charset=UTF-8");
        return header;
    }

    @Override
    public Map<String, String> getHttpExtraHeader(Map<String, Object> params) {
        return null;
    }

    protected <T> ResponseEntity<T> execute(String url,HttpMethod method, Map<String, Object> params, Class<T> target) {
        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(getHttpRequestBody(method,params), getHttpHeader(params));
        return restTemplate.exchange(url, method, httpEntity, target);
    }

    protected <T> ResponseEntity<T> execute(String url, Map<String, Object> params, Class<T> target) {
        return this.execute(url,getHttpMethod(),params,target);
    }

    private Map<String, Object> getHttpRequestBody(HttpMethod method,Map<String, Object> params) {
        if (HttpMethod.POST.equals(method)) {
            return params;
        }
        return null;
    }

    private LinkedMultiValueMap<String, String> getHttpHeader(Map<String, Object> params) {
        LinkedMultiValueMap<String, String> httpBasicHeader = getHttpBasicHeader();
        Map<String, String> httpExtraHeader = getHttpExtraHeader(params);
        if (httpExtraHeader != null) {
            httpExtraHeader.forEach(httpBasicHeader::add);
        }
        return httpBasicHeader;
    }
}
